package com.wlm.process.service.impl;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wlm.auth.service.SysUserService;
import com.wlm.model.process.Process;
import com.wlm.model.process.ProcessRecord;
import com.wlm.model.process.ProcessTemplate;
import com.wlm.model.system.SysUser;
import com.wlm.process.mapper.ProcessMapper;
import com.wlm.process.service.ProcessRecordService;
import com.wlm.process.service.ProcessService;
import com.wlm.process.service.ProcessTemplateService;
import com.wlm.security.custom.LoginUserInfoHelper;
import com.wlm.vo.process.ApprovalVo;
import com.wlm.vo.process.ProcessFormVo;
import com.wlm.vo.process.ProcessQueryVo;
import com.wlm.vo.process.ProcessVo;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.EndEvent;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

/**
 * <p>
 * 审批类型 服务实现类
 * </p>
 *
 * @author wlm
 * @since 2023-05-27
 */
@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class ProcessServiceImpl extends ServiceImpl<ProcessMapper, Process> implements ProcessService {

    @Autowired
    private ProcessMapper processMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ProcessTemplateService processTemplateService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ProcessRecordService processRecordService;

    @Autowired
    private HistoryService historyService;

    @Override
    public IPage<ProcessVo> selectPage(Page<ProcessVo> pageParam, ProcessQueryVo processQueryVo) {
        IPage<ProcessVo> page = processMapper.selectPage(pageParam, processQueryVo);
        return page;
    }

    @Override
    public void deployByZip(String deployPath) {
        // 定义zip输入流
        InputStream inputStream = this
                .getClass()
                .getClassLoader()
                .getResourceAsStream(deployPath);
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        // 流程部署
        Deployment deployment = repositoryService.createDeployment()
                .addZipInputStream(zipInputStream)
                .deploy();
    }

    @Override
    public void startUp(ProcessFormVo processFormVo) {
        // 1. 根据当前用户id获取用户信息
        SysUser sysUser = sysUserService.getById(LoginUserInfoHelper.getUserId());

        // 2. 根据审批模板id把模板信息查询出来
        ProcessTemplate processTemplate = processTemplateService.getById(processFormVo.getProcessTemplateId());

        // 3. 保存提交审批信息到业务表，oa_process
        Process process = new Process();
        // 将processFormVo中的数据复制到process中
        BeanUtils.copyProperties(processFormVo, process);
        // 其他的值
        String workNo = System.currentTimeMillis() + "";
        process.setProcessCode(workNo);
        process.setUserId(LoginUserInfoHelper.getUserId());
        process.setFormValues(processFormVo.getFormValues());
        process.setTitle(sysUser.getName() + "发起" + processTemplate.getName() + "申请");
        process.setStatus(1); // 审批中
        baseMapper.insert(process);

        // 4. 启动流程实例 - RuntimeService
        // 4.1 流程定义key
        String processDefinitionKey = processTemplate.getProcessDefinitionKey();
        // 4.2 业务key processId
        Long businessKey = process.getId();
        // 4.3 流程参数 form表单json数据，转换map集合
        String formValues = processFormVo.getFormValues();
        // formData
        JSONObject jsonObject = JSON.parseObject(formValues);
        JSONObject formData = jsonObject.getJSONObject("formData");
        // 遍历formData得到内容，放到map集合中
        Map<String, Object> map = new HashMap<>();
        for (Map.Entry<String,Object> entry:formData.entrySet()) {
            map.put(entry.getKey(), entry.getValue());
        }
        Map<String, Object> variables = new HashMap<>();
        variables.put("data", map);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey.toString(), variables);
        // 5. 查询下一个审批人(审批人可能是多个)
        List<Task> taskList = this.getCurrentTaskList(processInstance.getId());
        List<String> nameList = new ArrayList<>();
        for(Task task:taskList) {
            String assigneeName = task.getAssignee();
            SysUser user = sysUserService.getUserByUsername(assigneeName);
            String name = user.getName();
            nameList.add(name);
        }
        //TODO 6. 推送消息

        // 7. 业务和流程绑定
        process.setProcessInstanceId(processInstance.getId());
        process.setDescription("等待" + StringUtils.join(nameList.toArray(), ",") + "审批");
        processMapper.updateById(process);

        // 8. 记录审批记录
        processRecordService.record(process.getId(),1,"发起申请");
    }

    @Override
    public IPage<ProcessVo> findPending(Page<Process> pageParam) {
        // 1. 封装查询条件，根据当前登录的用户名称
        TaskQuery query = taskService.createTaskQuery().taskAssignee(LoginUserInfoHelper.getUsername())
                .orderByTaskCreateTime().desc();

        // 2. 调用方法分页条件查询，返回list集合，待办任务集合
        int begin = (int) ((pageParam.getCurrent() - 1) * pageParam.getSize());
        int size = (int) pageParam.getSize();
        List<Task> taskList = query.listPage(begin, size);

        // 3. 封装返回List集合数据 到List<ProcessVo>集合中
        List<ProcessVo> processList = new ArrayList<>();
        for(Task task: taskList) {
            // 从 task 获取流程实例id
            String processInstanceId = task.getProcessInstanceId();
            // 根据流程实例id获取实例对象
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            // 从流程实例对象获取业务key
            String businessKey = processInstance.getBusinessKey();
            if (StringUtils.isEmpty(businessKey)) continue;
            // 根据业务key获取Process对象
            Process process = baseMapper.selectById(businessKey);
            // 将Process对象 复制为ProcessVo对象
            ProcessVo processVo = new ProcessVo();
            BeanUtils.copyProperties(process, processVo);
            processVo.setTaskId(task.getId());

            // 将最终的ProcessVo对象放到集合中
            processList.add(processVo);

        }
        // 4. 封装IPage对象
        IPage<ProcessVo> page = new Page<ProcessVo>(pageParam.getCurrent(), pageParam.getSize(), query.count());
        page.setRecords(processList);

        return page;
    }

    /**
     * 查看审批详情信息
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> show(Long id) {
        // 1. 根据流程id获取流程信息Process
        Process process = baseMapper.selectById(id);

        // 2. 根据流程id获取流程记录信息
        LambdaQueryWrapper<ProcessRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProcessRecord::getProcessId, id);
        List<ProcessRecord> processRecordList = processRecordService.list(wrapper);

        // 3. 根据模板id查询模板信息
        ProcessTemplate processTemplate = processTemplateService.getById(process.getProcessTemplateId());

        // 4. 判断当前用户是否可以审批
        boolean isApprove = false;
        List<Task> taskList = this.getCurrentTaskList(process.getProcessInstanceId());
        for(Task task: taskList) {
            if (task.getAssignee().equals(LoginUserInfoHelper.getUsername())) {
                isApprove = true;
                break;
            }
        }

        // 5. 查询数据封装到map集合中
        Map<String, Object> map = new HashMap<>();
        map.put("process", process);
        map.put("processRecordList", processRecordList);
        map.put("processTemplate", processTemplate);
        map.put("isApprove", isApprove);
        return map;
    }

    @Override
    public void approve(ApprovalVo approvalVo) {
        // 1. 从approvalVo获取任务id, 根据任务id获取流程变量
        String taskId = approvalVo.getTaskId();
        Map<String, Object> variables = taskService.getVariables(taskId);
        for(Map.Entry<String,Object> entry:variables.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

        // 2. 判断审批状态值
        if (approvalVo.getStatus() == 1) {
            // 2.1 状态值 = 1 审批通过
            Map<String,Object> variable = new HashMap<>();
            taskService.complete(taskId, variable);
        }else {
            // 2.2 状态值 = -1 驳回，流程直接结束
            this.endTask(taskId);
        }

        // 3. 记录审批相关过程信息 oa_process_record
        String description = approvalVo.getStatus().intValue() == 1 ? "审批通过" : "审批驳回";
        processRecordService.record(approvalVo.getProcessId(), approvalVo.getStatus(), description);

        // 4. 查询下一个审批人，更新流程表记录 process表记录
        Process process = baseMapper.selectById(approvalVo.getProcessId());
        List<Task> taskList = this.getCurrentTaskList(process.getProcessInstanceId());
        // 4.1 判断是否有下一个审批人
        if(!CollectionUtils.isEmpty(taskList)) {
            List<String> assigneeList = new ArrayList<>();
            for(Task task: taskList) {
                String assignee = task.getAssignee();
                SysUser sysUser = sysUserService.getUserByUsername(assignee);
                assigneeList.add(sysUser.getName());

                //TODO 消息推送
            }
            // 更新process流程信息
            process.setDescription("等待" + StringUtils.join(assigneeList.toArray(), ",") + "审批");
            process.setStatus(1);
        } else {
            if (approvalVo.getStatus().intValue() == 1) {
                process.setDescription("审批通过(通过)");
                process.setStatus(2);
            } else {
                process.setDescription("审批通过(驳回)");
                process.setStatus(-1);
            }
        }
        baseMapper.updateById(process);

    }

    /**
     * 获取已处理的任务
     * @param pageParam
     * @return
     */
    @Override
    public IPage<ProcessVo> findProcessed(Page<java.lang.Process> pageParam) {
        // 封装查询条件
        HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery().taskAssignee(LoginUserInfoHelper.getUsername()).finished()
                .orderByTaskCreateTime().desc();

        // 调用方法条件分页查询，返回list集合
        int begin = (int) ((pageParam.getCurrent() - 1) * pageParam.getSize());
        int size = (int) pageParam.getSize();
        List<HistoricTaskInstance> list = query.listPage(begin, size);

        // 遍历返回list集合，封装List<ProcessVo>
        List<ProcessVo> processList = new ArrayList<>();
        for(HistoricTaskInstance item:list) {
            String processInstanceId = item.getProcessInstanceId();
            // 根据流程实例id查询获取process信息
            LambdaQueryWrapper<Process> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Process::getProcessInstanceId, processInstanceId);
            Process process = baseMapper.selectOne(wrapper);
            // process转换为ProcessVo
            ProcessVo processVo = new ProcessVo();
            BeanUtils.copyProperties(process, processVo);
            // 放到List
            processList.add(processVo);
        }

        // IPage封装分页查询所有数据，返回
        IPage<ProcessVo> pageModel = new Page<ProcessVo>(pageParam.getCurrent(), pageParam.getSize(), query.count());
        pageModel.setRecords(processList);
        return pageModel;
    }

    /**
     * 查询已发起信息
     * @param pageParam
     * @return
     */
    @Override
    public IPage<ProcessVo> findStarted(Page<ProcessVo> pageParam) {
        ProcessQueryVo processQueryVo = new ProcessQueryVo();
        processQueryVo.setUserId(LoginUserInfoHelper.getUserId());
        IPage<ProcessVo> pageModel = baseMapper.selectPage(pageParam, processQueryVo);
        return pageModel;
    }

    /**
     * 结束任务
     * @param taskId
     */
    private void endTask(String taskId) {
        // 1. 根据任务id获取任务对象 Task
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        // 2. 获取流程定义模型 BpmnModel
        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());

        // 3. 获取结束流向节点
        List<EndEvent> endEventList = bpmnModel.getMainProcess().findFlowElementsOfType(EndEvent.class);
        if (CollectionUtils.isEmpty(endEventList)) {
            return;
        }
        FlowNode endFlowNode = endEventList.get(0);
        // 4. 当前流向节点
        FlowNode currentFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(task.getTaskDefinitionKey());

        // 5. 清理当前流动方向
        currentFlowNode.getOutgoingFlows().clear();

        // 6. 创建新流向
        SequenceFlow newSequenceFlow = new SequenceFlow();
        newSequenceFlow.setId("newSequenceFlow");
        newSequenceFlow.setSourceFlowElement(currentFlowNode);
        newSequenceFlow.setTargetFlowElement(endFlowNode);
        List newSequenceFlowList = new ArrayList<>();
        newSequenceFlowList.add(newSequenceFlow);

        // 7. 当前节点指向新方向
        currentFlowNode.setOutgoingFlows(newSequenceFlowList);

        // 8. 完成当前任务
        taskService.complete(task.getId());

    }



    // 查询任务列表
    private List<Task> getCurrentTaskList(String id) {
        return taskService.createTaskQuery()
                .processInstanceId(id)
                .list();
    }
}
